const logger = require('../logger');
const db = require('../../db');

class Category {
    /*
    constructor() {

    }
    */


    /**
     * 分类列表
     */
    getCategoryList(req) {
        logger.data.info('model.category.getCategoryList req：', req.params);
        return new Promise(function (resolve, reject) {
            // let condition = {};
            db.category.findAndCountAll({
                // attributes: [],
                where: { status: 1 }, // 只取有效的分类
                order: [
                    ['update_time', 'desc']
                ],
            }).then(function (result) {
                resolve(result);
            }, function (err) {
                logger.error.error('model.category.getCategoryList error：', err);
                reject(err);
            });
        });
    }

    /**
     * 分类树
     */
    getCategoryTree(req) {
        logger.data.info('model.category.getCategoryTree req：', req.params);
        return new Promise(function (resolve, reject) {
            db.category.findAndCountAll({
                where: {},
                order: [
                    ['update_time', 'desc']
                ],
            }).then(function (result) {
                let treeList = [];
                // 把列表转换为树
                let categoryList = result.rows.filter(item => Number(item.category_id) !== 0);
                // 最多有四级
                let level1CategoryList = categoryList.filter(item => Number(item.category_level) === 1);
                level1CategoryList.forEach(level1 => {
                    let item1 = getTreeItem(level1);
                    let level2CategoryList = categoryList.filter(item => Number(item.parent_category_id) === level1.category_id);// 二级节点
                    level2CategoryList.forEach(level2 => {
                        let item2 = getTreeItem(level2);
                        let level3CategoryList = categoryList.filter(item => Number(item.parent_category_id) === level2.category_id);// 三级节点
                        level3CategoryList.forEach(level3 => {
                            let item3 = getTreeItem(level3);
                            let level4CategoryList = categoryList.filter(item => Number(item.parent_category_id) === level3.category_id);// 四级节点
                            level4CategoryList.forEach(level4 => {
                                let item4 = getTreeItem(level4);
                                item3.children.push(item4);
                            });
                            item2.children.push(item3);
                        });
                        item1.children.push(item2);
                    });
                    treeList.push(item1);
                });
                resolve(treeList);
            }, function (err) {
                logger.error.error('model.category.getCategoryTree error：', err);
                reject(err);
            });
        });
    }

    /**
     * 保存分类
     */
    saveCategory(req) {
        let reqData = req.body;
        let { category_id } = reqData;
        const now = new Date();
        const uid = req.userInfo.uid;
        logger.data.info('model.category.saveCategory req：', reqData);
        return new Promise(function (resolve, reject) {
            reqData.update_time = now;
            // 修改
            if (Number(category_id)) {
                reqData.updator = uid;
                logger.data.info('model.category.saveCategory update：', reqData);
                db.category.update(reqData, {
                    where: { category_id }
                }).then(result => {
                    resolve(result[0]);
                }).catch(e => {
                    logger.error.error('model.category.saveCategory update error：', e);
                    resolve('');
                });
            } else {
                // 新增
                reqData.creat_time = now;
                reqData.creator = uid;
                logger.data.info('model.category.saveCategory create：', reqData);
                db.category.create(reqData).then(result => {
                    resolve(result);
                }).catch(e => {
                    logger.error.error('model.category.saveCategory create error：', e);
                    resolve('');
                });
            }
        });
    }
}

function getTreeItem(category) {
    return {
        id: category.category_id,
        label: category.category_name,
        status: category.status,
        creat_time: category.creat_time,
        creator: category.creator,
        update_time: category.update_time,
        updator: category.updator,
        children: []
    };
}

module.exports = new Category();
